﻿using Newtonsoft.Json;
using RMS.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Filters;

namespace RMS.Common.Error
{
    public class WebAPIErrorAttribute : ExceptionFilterAttribute
    {

        /// <summary>
        /// 异常
        /// </summary>
        /// <param name="filterContext">异常上下文</param>
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            var result = new CommonOutPutVm();
            NLogHelper nlog = new NLogHelper();
            Exception Error = filterContext.Exception;
            #region 获取异常信息，入库保存
            try
            {
                ErrorLog log = Error.ToHttpErrorLog();
                result.Message = Error.GetInnerMessage();
                log.Save();
            }
            catch (Exception e)
            {
                result.Message = "异常处理错误：" + Error.Message;
                nlog.Error(Error);
                e.SaveLogException();
            }
            #endregion
            #region 返回错误信息对象输出错误信息
            finally
            {
                throw new System.Web.Http.HttpResponseException(filterContext.Request.CreateResponse(System.Net.HttpStatusCode.OK, result));
            }
            #endregion
        }
    }
}
